<?php

namespace Ignus\View\Node;

use Ignus\View\Node;
use Ignus\View\Compiler;
use Ignus\View\NodeInterface;

class SandboxedModule extends Module
{
    protected $usedFilters;
    protected $usedTags;
    protected $usedFunctions;

    public function __construct(Module $node, array $usedFilters, array $usedTags, array $usedFunctions)
    {
        parent::__construct($node->getNode('body'), $node->getNode('parent'), $node->getNode('blocks'),
                            $node->getNode('macros'), $node->getNode('traits'), $node->getAttribute('filename'),
                            $node->getLine(), $node->getNodeTag());

        $this->usedFilters = $usedFilters;
        $this->usedTags = $usedTags;
        $this->usedFunctions = $usedFunctions;
    }

    protected function compileDisplayBody(Compiler $compiler)
    {
        if (null === $this->getNode('parent')) {
            $compiler->write("\$this->checkSecurity();\n");
        }

        parent::compileDisplayBody($compiler);
    }

    protected function compileDisplayFooter(Compiler $compiler)
    {
        parent::compileDisplayFooter($compiler);

        $compiler
            ->write("protected function checkSecurity() {\n")
            ->indent()
            ->write("\$this->env->getExtension('sandbox')->checkSecurity(\n")
            ->indent()
            ->write(!$this->usedTags ? "array(),\n" : "array('".implode('\', \'', $this->usedTags)."'),\n")
            ->write(!$this->usedFilters ? "array(),\n" : "array('".implode('\', \'', $this->usedFilters)."'),\n")
            ->write(!$this->usedFunctions ? "array()\n" : "array('".implode('\', \'', $this->usedFunctions)."')\n")
            ->outdent()
            ->write(");\n");

        if (null !== $this->getNode('parent')) {
            $compiler
                ->raw("\n")
                ->write("\$this->parent->checkSecurity();\n");
        }

        $compiler
            ->outdent()
            ->write("}\n\n");
    }
}
